package com.zy.chat.config;

import com.zy.chat.constants.constants;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.QueueInformation;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


/**
 * @author zy
 * @date 2023/5/15 13:34
 */
@Component
public class RabbitMQMonitor {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Scheduled(fixedRate = 5000)
    public void monitor() {
        AmqpAdmin amqpAdmin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());
        QueueInformation queueInfo = amqpAdmin.getQueueInfo(constants.INSERT_QUEUE_NAME_SINGLEMSG);
        int messageCount = queueInfo.getMessageCount(); // 获取队列中消息的数量
        int deliveryCount = queueInfo.getConsumerCount(); // 获取队列中正在消费的消费者数量
        // 根据需要动态地设置消费者的线程数
        if (messageCount > 500 || deliveryCount < 5) {
            // 如果队列中的消息数超过100并且正在处理的消费者数小于5，则增加消费者线程数
            rabbitTemplate.setChannelTransacted(true);
            rabbitTemplate.setChannelTransacted(false);
        } else if (messageCount < 500 && deliveryCount > 5) {
            // 如果队列中的消息数少于50并且正在处理的消费者数大于10，则减少消费者线程数
            rabbitTemplate.setChannelTransacted(true);
            rabbitTemplate.setChannelTransacted(false);
        }
    }
}
